<template>
    <!-- <Dialog :app-dialog="appDialog"> -->

    <el-dialog v-model="appDialog.visible" :title="appDialog.title" :width="appDialog.width" @close="handleClose">
        <template #header>
            <div class="dialog_header">
                {{ appDialog.title }}
                <span v-if="props.limitNum" class="dialog-header-tip">
                    （因企微限制，引流员工上限为{{ props.limitNum }}人）
                </span>
            </div>
        </template>
        <div class="depart_box">
            <div class="depart_l">
                <el-input
                    v-model="searchName"
                    class="search_name"
                    placeholder="搜索成员、部门"
                    :prefix-icon="Search"
                    clearable
                    @input="handleSearch" />
                <el-button v-if="isExternal" style="margin-left: 20px" type="text" @click="getDepartList">
                    刷新页面
                </el-button>
                <el-tree-v2
                    ref="treeRef"
                    class="zw-tree-box"
                    :data="depart"
                    :props="defaultProps"
                    :filter-method="handleFilterMethod"
                    show-checkbox
                    :height="400"
                    @check-change="currentChange">
                    <template #default="{ node, data }">
                        <span class="prefix">
                            <el-icon v-if="data.type == 'user'" class="depart_member_icon">
                                <user-filled />
                            </el-icon>
                            <img v-else class="depart_icon mr2" src="/static/newDepart.png" alt="" />
                        </span>
                        <el-tooltip v-if="data.disabled" :content="data.select_msg" placement="top">
                            <span>{{ node.label }}</span>
                        </el-tooltip>
                        <span v-if="!data.disabled">{{ node.label }}</span>
                        <span v-if="data.type !== 'user'">（{{ data.user_count }}）</span>
                    </template>
                </el-tree-v2>
            </div>
            <div class="depart_r">
                <div class="depart_select_title">
                    <span>已选择的员工（{{ selectedMember.length }}）</span>
                    <el-button class="empty" link @click="emptyBtn">清空</el-button>
                </div>
                <el-scrollbar height="380px">
                    <div v-for="item in selectedMember" :key="item.id" class="seled_member">
                        <div class="item_member">
                            <el-icon v-if="item.type == 'user'" class="seled_icon">
                                <user-filled />
                            </el-icon>
                            <img v-else class="depart_icon" src="/static/newDepart.png" alt="" />
                            <span class="member_name">
                                {{ item.name }}
                                <span v-if="item.is_local == 1">(本地)</span>
                            </span>
                        </div>
                        <el-icon class="remove_icon" @click="delItem(item)">
                            <close />
                        </el-icon>
                    </div>
                </el-scrollbar>
            </div>
        </div>
        <template #footer>
            <el-button @click="appDialog.cancel">
                {{ appDialog.cancelText }}
            </el-button>
            <el-button type="primary" @click="appDialog.submit">
                {{ appDialog.submitText }}
            </el-button>
        </template>
    </el-dialog>
    <!-- </Dialog> -->
</template>
<script lang="ts" setup>
import { ref, reactive, watchEffect } from 'vue';
// import Dialog from '@/components/Dialog.vue';
import { Search, UserFilled } from '@element-plus/icons-vue';
import { ElMessage, ElTreeV2 } from 'element-plus';
import { getDepartUserInfo } from '@/api/common';
import { getSetionId } from '@/utils/utils';
import lodash, { set } from 'lodash';
const emit = defineEmits(['submit']);
const treeRef = ref<InstanceType<typeof ElTreeV2>>();
// 外部联系人权限 is_wx_follow_user  默认 1   全部 0   是 1   否  2
// 开启会话存档 is_open_session_archive  默认 0    全部 0   是 1   否  2
// 同时判断三个属性 has_authorization1：员工手机号；2，头像3，二维码      默认 1   全部 0   是 1   否  2(has_authorization默认为1由外部传入，0是默认查询全部，1是只查企微授权的)
// 选择选择人员数量 limitNum:  默认不限制人数，群裂变限制100人
//  is_local， （默认2，大东说的默认2），0 全部， 1 是本地员工， 2 非本地员工
const props = defineProps({
    is_local: {
        type: Number,
        default: 2
    },
    is_wx_follow_user: {
        type: Number,
        default: 1
    },
    is_open_session_archive: {
        type: Number,
        default: 0
    },
    has_authorization: {
        type: Number,
        default: 1
    },
    limitNum: {
        type: Number,
        default: null
    }
});
// 部门信息
// 选中人员新】
const selectedMember = ref([]);
// 弹框
const departVisble = ref(false);
const isCancel = ref(false);
const title = ref('选择员工');
const isExternal = ref(false); // 外部联系人
const isNotWxUser = ref(false); //是否绑定企微员工
const currentData = ref([]);

// 取消
const cancelHandel = () => {
    departVisble.value = false;
    searchName.value = '';
};
//确定
const submitHandel = () => {
    isCancel.value = false;
    emit('submit', selectedMember.value, isCancel.value);
    departVisble.value = false;
    searchName.value = '';
};
const appDialog = reactive({
    visible: departVisble,
    title: title,
    width: '800px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '保存'
});
const searchName = ref('');
const defaultProps = {
    children: 'children',
    label: 'name',
    disabled: 'disabled',
    value: 'd_u_unique_id'
};
const treeData: any[] = [];

const defaultExpandedKeys = reactive<any[]>([]);
const defaultExpandedLevel = 1; // 默认展开的层级
// 部门左侧树
const depart = ref<any>([]);
// 回显数据
const echoEdit = (data: any) => {
    const arr = getSetionId('id', data);
    treeRef.value?.setCheckedKeys(arr.map(item => 'U_' + item));
};
// 获取部门员工信息
watchEffect(() => {
    if (departVisble.value) {
        getDepartList();
    }
});
// 获取部门成员信息
const getDepartList = async () => {
    // 外部联系人权限 is_wx_follow_user  默认 1   全部 0   是 1   否  2
    // 开启会话存档 is_open_session_archive  默认 0    全部 0   是 1   否  2
    // 同时判断三个属性 has_authorization1：员工手机号；2，头像3，二维码      默认 1   全部 0   是 1   否  2
    //根据手机号查询员工信息
    const params = {
        is_wx_follow_user: props.is_wx_follow_user,
        is_open_session_archive: props.is_open_session_archive,
        has_authorization: props.has_authorization,
        is_local: props.is_local
    };
    const data: any[] = await getDepartUserInfo(params);
    const ids = getSetionId('id', selectedMember.value);
    const resTreeData = filterMember(data, ids);
    // console.log(resTreeData, 'resTreeData');
    treeData.splice(0, treeData.length, ...resTreeData);
    depart.value = resTreeData;
    treeRef.value!.setData(resTreeData);
    treeRef.value!.setExpandedKeys(defaultExpandedKeys); // 设置默认展开
    setTimeout(() => {
        echoEdit(selectedMember.value);
    });
};
// 过滤需要的人员信息
const filterMember = (data: any, ids?: any[], level = 1) => {
    data = Array.isArray(data) ? data : [data];
    const arr: any[] = [];
    data.forEach((item: any) => {
        item.level = level; // 添加层级
        const ids = getSetionId('id', selectedMember.value);
        item.check = ids.includes(item.id);
        if (item.users && item.users.length > 0) {
            item.members = item.users.length;
            if ((item.children && item.children.length == 0) || !item.children) {
                item.children = item.users;
            } else {
                item.children = Array.from(new Set([...item.children, ...item.users]));
            }
        }
        if (item.children && item.children.length > 0) {
            level <= defaultExpandedLevel && defaultExpandedKeys.push(item.d_u_unique_id); // 默认展开
            item.children = filterMember(item.children, ids, level + 1);
        }
        arr.push(item);
    });
    return arr;
};

const current = ref();
// 选择部门和员工
const currentChange = (data: any, node: any) => {
    seletData(data, node);
    current.value = data;
    if (data.check) {
        currentData.value.push(data.id);
    } else {
        const index = currentData.value.findIndex((v: any) => v === data.id);
        currentData.value.splice(index, 1);
    }
    goRefreshTree(data);
};
// 刷新树列表组件
const goRefreshTree = (node: any) => {
    // 目前el组件无刷新的特定方案，暂且使用直接重新显式设置数据的方式来模拟刷新
    //（展开折叠的方式对滚动条位置有影响）暂不采用
    // $focureUpdate方法无效
    treeRef.value?.setData(treeData);
};
// 删除选中成员信息
const removeItem = (data: any) => {
    const res = data.filter((item: any) => item.type !== 'department');
    const arr = getSetionId('id', res);
    const result = selectedMember.value.filter((item: any) => !arr.includes(item.id));
    selectedMember.value = result;
    depart.value = restoreDepart(data.id, depart.value, false);
};
// 遍历平铺数据
const treeToFlat = (data: any) => {
    const queue = JSON.parse(JSON.stringify(data));
    const result = [];
    while (queue.length) {
        const node = queue.shift();
        if (node.children?.length) {
            queue.push(...node.children);
            Reflect.deleteProperty(node, 'children');
        }
        result.push(node);
    }
    return result;
};
// 右侧删除的按钮
const delItem = (data: any) => {
    const res = treeToFlat([data]);
    removeItem(res);
    treeRef.value.setChecked(`U_${data.id}`, false);
};
// 选中后放在右边的数据
const seletData = (item: any, node: any) => {
    if (node) {
        selectedMember.value.push(item);
        const arrlist = treeToFlat(selectedMember.value);
        const b = arrlist.filter((item: any) => {
            return item.type != 'department' && (item.disabled === false || !item.disabled);
        });
        const obj = {};
        selectedMember.value = b.reduce((cur, next) => {
            obj[next.id] ? '' : (obj[next.id] = true && cur.push(next));
            return cur;
        }, []);
        if (props.limitNum !== null && props.limitNum > 0) {
            if (selectedMember.value.length > props.limitNum) {
                delItem(item);
                ElMessage.error(`因企微限制，引流员工上限为${props.limitNum}人`);
            }
        }
    } else {
        const res = treeToFlat([item]);
        removeItem(res);
    }
};
// 清空按钮
const emptyBtn = () => {
    searchName.value = '';
    handleSearch();
    selectedMember.value = [];
    treeRef.value!.setCheckedKeys([]);
};

const handleSearch = lodash.debounce(() => {
    treeRef.value!.filter(searchName.value);
    // 如果是清空了数据，则默认只展开顶级的
    if (!searchName.value) {
        treeRef.value!.setExpandedKeys(defaultExpandedKeys); // 设置默认展开
    }
}, 500);
const handleFilterMethod = (query: string, node: any) => {
    return node.name!.includes(query);
};
// 关闭弹窗时，清空查询项
const handleClose = () => {
    treeRef.value?.filter(searchName.value);
};
//打开员工弹窗时，根据右边的数据确定左侧数的选中- val:true
// 删除右侧选中成员 恢复左边
const restoreDepart = (id: any, data: any, val?: any) => {
    return data.map((item: any) => {
        if (item.id == id) {
            item.check = val ? true : false;
        } else {
            if (item.children && item.children.length > 0) {
                item.children = val ? restoreDepart(id, item.children, true) : restoreDepart(id, item.children, false);
            }
        }
        return item;
    });
};
// 左侧树状态设置为false
const clean = (data: any) => {
    const arr: any[] = [];
    data.forEach((item: any) => {
        item.check = false;
        if (item.children && item.children.length > 0) {
            item.children = clean(item.children);
        }
        arr.push(item);
    });
    return arr;
};
const leftchecktree = (id?: any) => {
    depart.value = restoreDepart(id, depart.value, true);
};
// 查找部门的成员信息
const restore = (data: any) => {
    const arr: any[] = [];
    data.map((item: any) => {
        item.check = false;
        if (item.children && item.children.length > 0) {
            item.children = restore(item.children);
        }
        arr.push(item);
    });
    return arr;
};
defineExpose({
    departVisble,
    appDialog,
    title,
    leftchecktree,
    clean,
    depart,
    selectedMember,
    removeItem,
    isExternal,
    isNotWxUser,
    currentData
});
</script>
<style lang="scss" scoped>
.depart_box {
    display: flex;

    .depart_member_icon {
        vertical-align: bottom;
        margin-right: 2px;
    }

    .depart_icon {
        width: 15px;
        vertical-align: middle;
    }

    .mr2 {
        margin-right: 2px;
    }
}

.depart_l {
    width: 350px;
    padding-right: 10px;
    border-right: 1px solid #eaeaea;

    .search_name {
        // width: 259px;
        width: 100%;
        margin-bottom: 10px;
    }

    .custom-tree-node {
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .is_member {
        // 不可全选样式
        :deep(.el-tree-node) {
            .is-leaf + .el-checkbox .el-checkbox__inner {
                display: inline-block;
            }

            .el-checkbox .el-checkbox__inner {
                display: none;
            }
        }
    }
}

.depart_r {
    padding: 10px 20px;
    flex: 1;

    .depart_select_title {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20px;

        .empty {
            color: #ff6b00;
        }
    }

    .el-scrollbar {
        height: auto;
    }

    .seled_member {
        line-height: 30px;
        display: flex;
        font-size: 14px;
        padding: 0 5px;
        align-items: center;
        justify-content: space-between;

        &:hover {
            background-color: rgb(255 107 0 / 9.02%);
        }

        .item_member {
            display: flex;
            align-items: center;

            .seled_icon {
                color: #ff6b00;
            }
        }

        .member_name {
            margin-left: 2px;
        }

        .remove_icon {
            cursor: pointer;

            &:hover {
                transform: scale(1.23);
            }
        }
    }
}

:deep(.zw-tree-box) {
    .el-vl__wrapper {
        position: initial;
        overflow-x: scroll;

        .el-vl__window {
            width: 700px;
        }
    }
}

.dialog-header-tip {
    font-size: 14px;
    color: #ccc;
}
</style>
